import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { HeroService } from '../../../../services/hero.service';
import { NzMessageService,NzModalService } from 'ng-zorro-antd';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';

@Component({
  selector: 'app-editacount',
  templateUrl: './editacount.component.html',
  styleUrls: ['./editacount.component.css']
})
export class EditacountComponent implements OnInit {

  btn_loading=false;
  validateForm: FormGroup;
  rolelist:Array<any>;
  roleCheck:Array<any>=[];
  roleChecked:Array<any>=[];
  roleCheckIds:Array<any>=[];
  checkUsername:number;

  // public radioValue:string="0";

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
      this.validateForm.controls[ i ].updateValueAndValidity();
    }
  }

  constructor(private heroService: HeroService,
              private fb: FormBuilder,
              private router: Router,
              private route: ActivatedRoute,
              private message: NzMessageService,
              private modalService: NzModalService) { }

  phoneNUmberValidator = (control: FormControl): { [ s: string ]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (!(/^1\d{10}$/.test(control.value))) {
      return { confirm: true, error: true };
    }
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [ null, [ Validators.required ] ],
      name: [ null, [ Validators.required ] ],
      phoneNumberPrefix: [ '+86' ],
      phoneNumber: [ null, [ Validators.required ] ],
      checkOptions: [ null ],
      remark: [ null ]
    });
    const id = this.route.snapshot.paramMap.get('id');
    // 回显账号内容
    let url=host+"/main/merchantSubAcount/add?id="+id;
    this.heroService.get(url).then(result=>{
        if(result.code == 0){
          this.validateForm.get('username').setValue(result.data.bean.username);
          this.validateForm.get('name').setValue(result.data.bean.name);
          this.validateForm.get('phoneNumber').setValue(result.data.bean.mobile);
          this.validateForm.get('remark').setValue(result.data.bean.remark);
          this.rolelist=result.data.roles;
          this.roleChecked=result.data.myRoles;
          this.rolelist.map((item) => {
            this.roleCheck.push({label:item.name, value: item.id});
          })
          this.roleChecked.map((item) => {
            this.roleCheck.map( (item2) => {
                if(item2.value == item.rid){
                  item2.checked = true;
                }
            })
          })
          // console.log(this.roleCheck);
          this.validateForm.get('checkOptions').setValue(this.roleCheck);
        }else{
          this.modalService.error({
            nzTitle: '提示',
            nzContent: result.msg
          });
        }
    })
  }

  addAcount() {
    const id = this.route.snapshot.paramMap.get('id');
    if(this.validateForm.status=="VALID" && this.checkUsername !=-1){
      this.btn_loading=true;
      let url=host+"/main/merchantSubAcount/save";
      let model='id='+id+'&username='+this.validateForm.value.username+'&name='+this.validateForm.value.name+'&mobile='+this.validateForm.value.phoneNumber+'&roleIds='+this.roleCheckIds+'&remark='+this.validateForm.value.remark;
      this.heroService.post(url,model).then(result=>{
          this.btn_loading=false;
          if(result.code==0){
            this.message.success('修改成功');
            this.router.navigate(['/main/acount']);
          }else{
            this.modalService.error({
              nzTitle: '提示',
              nzContent: 'result.msg'
            });
          }
      })
    }
  }

  log(): void {
    this.roleCheckIds=[];
    this.validateForm.get('checkOptions').value.filter((item) => item.checked).map( (item) => {
      this.roleCheckIds.push(item.value);
    })
    console.log(this.roleCheckIds);
  }
  checkMobile(){
    this.validateForm.get('phoneNumber')!.setValidators(this.phoneNUmberValidator);
    this.validateForm.get('phoneNumber')!.markAsDirty();
    this.validateForm.get('phoneNumber')!.updateValueAndValidity();
  }
  clearCheckMobile(){
    this.validateForm.get('phoneNumber')!.clearValidators();
    this.validateForm.get('phoneNumber')!.markAsPristine();
    this.validateForm.get('phoneNumber')!.updateValueAndValidity();
  }
  checkUser(){
    if(this.validateForm.value.username){
      //只能输入字母、数字、下划线的组合
      let regex=/^[a-zA-Z0-9][\w-_]{5,13}$/g;
      if(regex.test(this.validateForm.value.username)){
        this.checkUsername=0;
      }else{
        this.checkUsername=-1;
      }
    }
  }
  backPrevent(){
    return false;
  }
}